package com.aac.rabbitrfc.service.impl;

import com.aac.rabbitrfc.dao.BaseDao;
import com.aac.rabbitrfc.pojo.DatDocument;
import com.aac.rabbitrfc.service.DatDocumentService;
import com.aac.rabbitrfc.util.DatDocumentUtil;
import com.aac.rabbitrfc.util.XmlDataUtil;
import org.json.JSONObject;
import org.json.XML;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class DatDocumentServiceImpl implements DatDocumentService {

    private static final Logger LOG = LoggerFactory.getLogger(DatDocumentService.class);

    @Autowired
    private BaseDao<DatDocument> baseDao;

    @Override
    public Map<String, Object> getDocumentByField(String appId, String formName, String fieldName, String fieldValue) {
        Map<String, Object> results = new HashMap<>();
        String sql = "select * from DAT_DOCUMENT where app_id=? and form_Name=? and " +
                "EXTRACTVALUE(DOCUMENT_DATA,'//root/" + fieldName + "')=?";
        List<String> params = new ArrayList<>();
        params.add(appId);
        params.add(formName);
        params.add(fieldValue);
        List<DatDocument> datDocuments = baseDao.executeJDBCSqlQuery(sql, DatDocument.class, params);
        DatDocument datDocument = null;
        if (datDocuments.isEmpty()) {
            LOG.warn("在应用库中没有文档！");
        } else {
            datDocument = datDocuments.get(0);
        }
        if (datDocument != null) {
            String xmlData = XmlDataUtil.toString(datDocument.getDocument());
            JSONObject jsoDocData = XML.toJSONObject(xmlData);
            if (jsoDocData.has("root")) {
                JSONObject root = jsoDocData.getJSONObject("root");
                Iterator it = root.keys();
                while (it.hasNext()) {
                    String key = (String) it.next();
                    Object value = root.get(key);
                    Object data = DatDocumentUtil.parseValue(value);
                    if (data != null) {
                        if (data instanceof ArrayList) {
                            results.put(key, ((ArrayList<?>) data).get(0));
                        } else {
                            results.put(key, data);
                        }
                    }
                }
            }
        }
        return results;
    }

}
